package com.prj.config;

import java.util.Map;

import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.wrapper.MapWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapper;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.autoconfigure.ConfigurationCustomizer;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

import cn.hutool.core.util.StrUtil;

@Configuration
public class MybatisPlusConfig {
	
	/**
	 * 分页插件
	 * @return
	 */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        return interceptor;
    }
    
    /**
     * 封装map时key转驼峰
     * @return
     */
    @Bean
    public ConfigurationCustomizer mybatisConfigurationCustomizer(){
        ConfigurationCustomizer config = (configureation) -> {
        	configureation.setObjectWrapperFactory(new ObjectWrapperFactory() {
				@Override
				public boolean hasWrapperFor(Object object) {
					return object != null && object instanceof Map;
				}
				
				@Override
				public ObjectWrapper getWrapperFor(MetaObject metaObject, Object object) {
					return new CustomWrapper(metaObject,(Map)object);
				}
			});
        };
        return config;
    }
    
}

class CustomWrapper extends MapWrapper {
    public CustomWrapper(MetaObject metaObject, Map<String, Object> map) {
        super(metaObject, map);
    }
    @Override
    public String findProperty(String name, boolean useCamelCaseMapping) {
        if(useCamelCaseMapping){
            return StrUtil.toCamelCase(name);
        }
        return name;
    }
}
